//
//  FSWaitReceiveController.m
//  Trade
//
//  Created by 刘沿 on 16/4/11.
//  Copyright © 2016年 刘沿. All rights reserved.
//
#import "ckUnDonelistCell.h"
#import "FSWaitReceiveController.h"

@interface FSWaitReceiveController ()
@property(nonatomic,strong)NSMutableArray * dataArray;

@property(nonatomic,assign)BOOL isSearching;

@property(nonatomic,copy)NSString * searchText;
@property(nonatomic,strong)NSDictionary * adic;

@end

@implementation FSWaitReceiveController

- (void)viewDidLoad {
    self.isNeedRefresh = YES;
    [super viewDidLoad];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    [self setRightItem];
    [self.tableView headerBeginRefreshing];

}

-(void)setRightItem{
    if (self.vcType == AlreadySignType || self.vcType == SenderSinType) {
        UIBarButtonItem * rightIem = [[UIBarButtonItem alloc] initWithTitle:@"搜索" style:UIBarButtonItemStylePlain target:self action:@selector(searchAction)];
        self.navigationItem.rightBarButtonItem = rightIem;
    }
    
}

#pragma mark 搜素
-(void)searchAction{
    
    [UIAlertView showWithTitle:@"搜索" message:nil style:UIAlertViewStylePlainTextInput cancelButtonTitle:@"取消" otherButtonTitles:@[@"确定"] tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
        [self.view endEditing:YES];
        
        if (buttonIndex == 1) {
            UITextField * textField = [alertView textFieldAtIndex:0];
            if (textField.text.length !=0) {
                
                [self.contentsArray removeAllObjects];
                self.isSearching = YES;
                self.currentPage = 1;
                [self loadSearchData:textField.text];
            }
            
        }
        
    }];
    
}


-(void)requestData{
    
    if (self.isSearching) {
        self.currentPage = 1;
        self.searchText = self.searchText.length !=0 ? self.searchText : @"";
        [self loadSearchData:self.searchText];
        
    }else{
        NSString * method = nil;
        NSString * URL = nil;
        if (self.vcType == WaitForSignType) { //待收文件
            method = KexhcangePageMethod;
            URL = KexchexchangeURL;
            self.title = @"待收文件";
        }else if (self.vcType == AlreadySignType){ //已收文件
            method = KreceivedExhcangePageMethod;
            URL = KexchexchangeURL;
            self.title = @"已收文件";
        }else if (self.vcType == SenderSinType){ //已发文件
            method = KsendExhcangePageMethod;
            URL = KexchexchangeURL;
            self.title = @"已发文件";
        }else if(self.vcType == WaitForReadType){//待阅
            method = KReadFilePage;
            URL = KexchgeneralURL;
            self.title = @"待阅文件";
        }
        self.currentPage = 1;
        NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
        NSArray * array = @[@{@"userId":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
        __weak typeof(self) weakSelf = self;
        [HttpTools requestWithURL:URL arrays:array method:method success:^(id JSON) {
   if (self.currentPage ==1) {
            [self.dataArray removeAllObjects];
        }
      _dataArray =   [NSMutableArray array];
        NSArray *array = JSON[@"data"];
        _adic= JSON[@"display"];
        self.totalNumber =[JSON[@"number"] intValue];
 if(JSON[@"number"]){

self.title = [NSString stringWithFormat:@"%@(%@)",self.title,JSON[@"number"]
       ];}
       else{

self.title = [NSString stringWithFormat:@"%@",self.title
       ];
       

       }
       

         for (NSDictionary *dic in array) {
    NSDictionary *dict = dic;
    [_dataArray addObject:dict];
    
}
NSLog(@"%@",JSON);
_adic= JSON[@"display"];

            [weakSelf.tableView headerEndRefreshing];
            [weakSelf.tableView reloadData];
            weakSelf.currentPage++;
        } failure:^(NSError *error) {
            [weakSelf.tableView headerEndRefreshing];
        }];
    }
}


-(void)loadSearchData:(NSString*)text{
    NSString * method = nil;
    self.searchText = text;
    if (self.vcType == WaitForSignType) { //待收文件
        method = KCollectSearchMethod;
    }else if (self.vcType == AlreadySignType){ //已收文件
        method = KReceivedSearchMethod;
    }else if (self.vcType == SenderSinType){ //已发文件
        method = KPostedSearchMethod;
    }
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"Condition":text},@{@"userId":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
    __weak typeof(self) weakSelf = self;
    [HttpTools requestWithURL:KexchangeSubstanceURL arrays:array method:method success:^(id JSON) {
  if (self.currentPage ==1) {
            [self.dataArray removeAllObjects];
        }
        _adic= JSON[@"display"];

      _dataArray =   [NSMutableArray array];
        NSArray *array = JSON[@"data"];
if(JSON[@"number"]){

self.title = [NSString stringWithFormat:@"%@(%@)",self.title,JSON[@"number"]
       ];}
       else{

self.title = [NSString stringWithFormat:@"%@",self.title
       ];
       

       }

         for (NSDictionary *dic in array) {
    NSDictionary *dict = dic;
    [_dataArray addObject:dict];
    
}

        [weakSelf.tableView footerEndRefreshing];
        [weakSelf.tableView reloadData];
        weakSelf.currentPage++;
        
        if (self.tableView.headerRefreshing) {
            [self.tableView headerEndRefreshing];
        }
        if (self.tableView.footerRefreshing) {
            [self.tableView footerEndRefreshing];
        }
        
    } failure:^(NSError *error) {
        if (self.tableView.headerRefreshing) {
            [self.tableView headerEndRefreshing];
        }
        if (self.tableView.footerRefreshing) {
            [self.tableView footerEndRefreshing];
        }
    }];
    
    
}
//加载更多
-(void)requestMoreData{
    
    if (self.isSearching) {
        self.searchText = self.searchText.length !=0 ? self.searchText : @"";
        [self loadSearchData:self.searchText];
        
    }else{
        NSString * method = nil;
        NSString * URL = nil;
             if (self.vcType == WaitForSignType) { //待收文件
            method = KexhcangePageMethod;
            URL = KexchexchangeURL;
            self.title = @"待收文件";
        }else if (self.vcType == AlreadySignType){ //已收文件
            method = KreceivedExhcangePageMethod;
            URL = KexchexchangeURL;
            self.title = @"已收文件";
        }else if (self.vcType == SenderSinType){ //已发文件
            method = KsendExhcangePageMethod;
            URL = KexchexchangeURL;
            self.title = @"已发文件";
        }else if(self.vcType == WaitForReadType){//待阅
            method = KReadFilePage;
            URL = KexchgeneralURL;
            self.title = @"待阅文件";
        }        NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
        NSArray * array = @[@{@"userId":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
        __weak typeof(self) weakSelf = self;
        [HttpTools requestWithURL:URL arrays:array method:method success:^(id JSON) {
                        NSArray *array = JSON[@"data"];

          for (NSDictionary *dic in array) {
    NSDictionary *dict = dic;
    [_dataArray addObject:dict];
    
}
_adic= JSON[@"display"];

       self.title = [NSString stringWithFormat:@"%@(%@)",self.title,JSON[@"number"]];
     self.currentPage++;
            [weakSelf.tableView footerEndRefreshing];
            [weakSelf.tableView reloadData];
            weakSelf.currentPage++;
        } failure:^(NSError *error) {
            [weakSelf.tableView footerEndRefreshing];
        }];

    }
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
//    static  NSString * cellId = @"Cellid";
//    FSWaitReceiveCell * cell = [tableView dequeueReusableCellWithIdentifier:cellId];
//    if (cell == nil) {
//        cell = [[[NSBundle mainBundle] loadNibNamed:@"FSWaitReceiveCell" owner:self options:nil] lastObject];
//    }
//    FSWaitReceiveModel * model = self.contentsArray[indexPath.row];
//    cell.titleLabel.text = model.subject;
//    cell.titleLabel.numberOfLines = 2;
//    if (model.exchangeCategory && model.exchangeUnit) {
//        cell.desLabel.text = [NSString stringWithFormat:@"%@/%@/%@",model.exchangeTime,model.exchangeCategory,model.exchangeUnit];
//    }else{
//        cell.desLabel.text = [NSString stringWithFormat:@"%@",model.exchangeTime];
//    }
//    
//    return cell;
 static NSString *CellIdentifier = @"Cell";  

    ckUnDonelistCell *cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
  if (cell==nil) {  
        cell=[[ckUnDonelistCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    
 NSDictionary *dic = self.dataArray[indexPath.row];
    cell.dic = dic;
        cell.adic = _adic;

    cell.number = [NSString stringWithFormat:@"%ld",(long)indexPath.row+1];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    FSWaitReceiveModel * model = self.contentsArray[indexPath.row];
//    CGFloat height = 0;
//    height = [OAToolBox heightbyString:model.subject font:14 minsWidth:55];
//    
//    return 8 + height + 5 + 21 +8;
  NSDictionary *dic = self.dataArray[indexPath.row];

    CGFloat  titleFloat  = [OAToolBox sizebyText:dic[@"subject"] font:15 minsWidth:60];

    return  titleFloat  +75+10;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//    FSWaitReceiveModel * model = self.contentsArray[indexPath.row];
            NSDictionary *dic = self.dataArray[indexPath.row];

    if (self.vcType == WaitForSignType) {
        
        [UIAlertView showWithTitle:nil message:@"确认是否签收" cancelButtonTitle:@"否" otherButtonTitles:@[@"是"] tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
            if (buttonIndex == 1) {
                MBProgressHUD * hud =  [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                hud.labelText = @"签收中";
                NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
                NSArray * array = @[@{@"userId":userId},@{@"unid":dic[@"unid"]}];
                __weak typeof(self) weakSelf = self;
                [HttpTools requestWithURL:KexchexchangeURL arrays:array method:KsignExhcangeMethod success:^(id JSON) {
                    [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
                    [weakSelf.view.window makeToast:@"签收成功"];
                    FSWaitDetailController * detaiVC = (FSWaitDetailController*)[self.storyboard instantiateViewControllerWithIdentifier:@"WaitDetail"];
                    detaiVC.exchangeForm = dic[@"form"];
                    detaiVC.identifier = dic[@"unid"];
                    detaiVC.vcType = self.vcType;
                    [self refreshData]; //刷新数据
                        detaiVC.hidesBottomBarWhenPushed = YES;

                    [self.navigationController pushViewController:detaiVC animated:YES];
                    
                } failure:^(NSError *error) {
                    [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
                    [weakSelf.view.window makeToast:@"签收失败"];
                }];
            }
            
        }];
    }else if (self.vcType == AlreadySignType || self.vcType == SenderSinType || self.vcType == WaitForReadType){
        FSWaitDetailController * detaiVC = (FSWaitDetailController*)[self.storyboard instantiateViewControllerWithIdentifier:@"WaitDetail"];
        detaiVC.exchangeForm =dic[@"form"];

        detaiVC.identifier = dic[@"unid"];
        detaiVC.vcType = self.vcType;
                                detaiVC.hidesBottomBarWhenPushed = YES;

        [self.navigationController pushViewController:detaiVC animated:YES];
    }
    
}


@end















